// const fs = require('fs')
const path = require('path')
// const webpack = require('webpack')
const WebpackBar = require('webpackbar')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin')
const ESLintPlugin = require('eslint-webpack-plugin')

const devMode = process.env.NODE_ENV !== 'production';
const pathResolve = pathUrl => path.join(__dirname, '..', pathUrl)

const plugins = [
  new WebpackBar({
    profile: true
  }),
  new CleanWebpackPlugin(),
  new HtmlWebpackPlugin({
    template: path.resolve(__dirname, "../public/index.html"),
  }),
  new ESLintPlugin({
    fix: true,
    extensions: ['ts', 'tsx', 'js', 'jsx'],
  }),
]

// const files = fs.readdirSync(path.resolve(__dirname, '../dll'))
// files.forEach(file => {
//   if (/.*.dll.js/.test(file)) {
//     plugins.unshift(
//       new AddAssetHtmlWebpackPlugin({
//         filepath: path.resolve(__dirname, '../dll/', file),
//         publicPath: '/'
//       }),
//     )
//   }
//   if (/.*.manifest.json/.test(file)) {
//     plugins.unshift(
//       new webpack.DllReferencePlugin({
//         manifest: path.resolve(__dirname, '../dll/', file)
//       }),
//     )
//   }
// })

module.exports = {
  entry: { app: path.resolve(__dirname, '../src/index.tsx') },
  stats: { children: false },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'], // 引入时不写后缀名默认引入这两种文件类型
    mainFiles: ['index'], // 引入某个文件夹下的文件时,如果不写具体文件,则引入index,可以写数组,写在前面的优先级高
    alias: { // 配置路径别名
      '@@': pathResolve('.'),
      '@': pathResolve('src'),
      '@assets': pathResolve('src/assets'),
      '@common': pathResolve('src/common'),
      '@components': pathResolve('src/components'),
      '@hooks': pathResolve('src/hooks'),
      '@pages': pathResolve('src/pages'),
      '@redux': pathResolve('src/redux'),
      '@service': pathResolve('src/service'),
      '@store': pathResolve('src/reducer'),
      '@action': pathResolve('src/action'),
      '@routes': pathResolve('src/routes'),
      '@utils': pathResolve('src/utils'),
      '@styles': pathResolve('src/styles'),
    },
  },
  module: {
    rules: [
      {
        test: /\.([jt])sx?$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              exclude: /node_modules/,
              plugins: [devMode && require.resolve('react-refresh/babel')].filter(Boolean)
            }
          },
          // {
          //   loader: 'eslint-loader',
          //   options: {
          //     enforce: 'pre',
          //     fix: true,
          //   }
          // }
        ],
      },
      {
        test: /\.(less|css)$/,
        use: [
          {
            loader: devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2,
              modules:  {
                auto: /\.module\.\w+$/i, // 只有文件名中包含module的less文件才开启模块化
                localIdentName: "[local]_[hash:base64:5]"
              },
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: () => [
                require('autoprefixer')({
                  "overrideBrowserslist": [
                    "> 0.01%",
                    "last 2 versions",
                    "not ie <= 8"
                  ],
                })
              ]
            }
          },
          {
            loader: 'less-loader'
          }
        ],
      },
      {
        test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg)$/,
        type: 'asset',
        generator: {
          // [ext]前面自带"."
          filename: '[name]_[hash:6].[ext]',
        },
        use: [

          // {
          //   loader: 'url-loader',
          //   options: {
          //     name: '[name]_[hash:base64:6].[ext]',
          //     outputPath: 'assets/',
          //     limit: 2048
          //   }
          // }
        ]
      },
    ]
  },
  plugins,

  optimization: {

    usedExports: true, // treeShaking

    splitChunks: {
      chunks: "all", // async为只对异步引入模块有效,initial为只对同步引入生效,如果想要同步异步都生效,则改为all,同时需要对cacheGroups中的vendors进行配置
      minSize: 20000, // 引入的包大于30kb才会帮助我们做代码分割
      minChunks: 1, // 当一个模块被引入至少多少次之后才会进行分割
      maxSize: 50000, // 如果引入的模块大于50kb,那么会尝试二次分割,例如引入的模块为1Mb,那么会尝试将该模块分割为20个20kb的模块
      maxAsyncRequests: 5, // 同时加载的模块数,例如我引入了10个模块,只会对前5个进行分割,超过的就不会再分割了
      maxInitialRequests: 3, // 入口文件做代码分割,只会分割三个文件
      automaticNameDelimiter: '~', // 文件生成时文件名中间的连接符
      // name: true, // cacheGroups中配置的name有效
      cacheGroups: { // 将符合某个组的要求的js文件打包到一个文件中去
        vendors: {
          test: /[\\/]node_modules[\\/]/, // 引入的库是否在node_modules下,如果是,就将该组件打包到vendors的组里去
          priority: -10, // 优先级,例如引入三方包,希望三方包被分割的要求按照vendors的配置来分割,就不会按照default的配置分割了
          name: 'vendors' // 打包后的文件名
        },
        default: false
      }
    }
  },
  output: {
    publicPath: '/',
    filename: 'script/[name].js',
    chunkFilename: 'script/[name].js', // 非入口文件打包后的文件名
    path: path.resolve(__dirname, '../dist')
  }
}
